package com.teamone.etl.taskmanager.util;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.*;

/**
 * @Description
 * @Author ZhaoPeiJie
 * @Date 2021/1/9 14:11
 * @Version 1.0
 */
public class ThreadManager {
    /**
     * 通过ThreadPoolExecutor的代理类来对线程池的管理
     */
    private static ThreadPollProxy threadPollProxy;

    public static ThreadPollProxy getThreadPollProxy(){
        synchronized (ThreadPollProxy.class) {
            if(threadPollProxy == null){
                threadPollProxy = new ThreadPollProxy(3,6,1000);
            }
        }
        return threadPollProxy;
    }

    public static class ThreadPollProxy{
        private ThreadPoolExecutor poolExecutor;//线程池执行者
        private int corePoolSize;//核心线程数
        private int maximumPoolSize;//最大线程数
        private long keepAliveTime;//线程存活时间

        public ThreadPollProxy(int corePoolSize,int maximumPoolSize,long keepAliveTime){
            this.corePoolSize = corePoolSize;
            this.maximumPoolSize = maximumPoolSize;
            this.keepAliveTime = keepAliveTime;
        }
        public void execute(Runnable runnable){
            ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
                    .setThreadFactory(Executors.defaultThreadFactory())
                    .setNameFormat("ThreadManager-Thread-%d")
                    .build();
            if(poolExecutor == null || poolExecutor.isShutdown()){
                poolExecutor = new ThreadPoolExecutor(
                        corePoolSize,
                        maximumPoolSize,
                        keepAliveTime,
                        TimeUnit.MILLISECONDS,
                        new LinkedBlockingDeque<>(),
                        namedThreadFactory);
            }
            poolExecutor.execute(runnable);
            poolExecutor.shutdown();
        }
    }
}
